package com.example.example_scanmusic;

import java.io.File;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

public class MediaScanner {

    private static final String TAG = MediaScanner.class.getSimpleName();
    //扫描类的对象
    private MediaScannerConnection mConn = null;
    //扫描回调
    private SannerClient mClient = null;
    //需要扫描的文件或者文件夹
    private File mFile = null;
    //mimeType
    private String mMimeType = null;

    /**
     * 构造方法初始化MediaScannerConnection SannerClient
     */
    public MediaScanner(Context context) {
        if (mClient == null) {
            mClient = new SannerClient();
        }
        if (mConn == null) {
            mConn = new MediaScannerConnection(context, mClient);
        }
    }

    class SannerClient implements
            MediaScannerConnection.MediaScannerConnectionClient {
    	//扫描service被创建并连接
        public void onMediaScannerConnected() {
        	Log.e(TAG, "onMediaScannerConnected");
            if (mFile == null) {
                return;
            }
            scan(mFile, mMimeType);
        }


        /**
         * 递归扫描文件
         */
        private void scan(File file, String type) {
            Log.e(TAG, "scan " + file.getAbsolutePath());
            if (file.isFile()) {//判断是否为文件,如果为文件则扫描,添加到媒体数据库
                mConn.scanFile(file.getAbsolutePath(), null);
                return;
            }
            File[] files = file.listFiles();//如果为文件夹,获得文件夹数组
            if (files == null) {
                return;
            }
            for (File f : file.listFiles()) {//从文件夹数组获取所有文件,递归遍历所有文件
            	Log.e(TAG, "scan " + f.getAbsolutePath());
                scan(f, type);
            }
        }

		@Override
		public void onScanCompleted(String path, Uri uri) {
			Log.e(TAG, "onScanCompleted");
			//扫描完成之后断开扫描服务
			mConn.disconnect();
		}
    }

    /**
     * 扫描指定文件夹媒体文件
     */
    public void scanFile(File file, String mimeType) {
        mFile = file;
        mMimeType = mimeType;
        //开启扫描服务
        mConn.connect();
    }

}
